import { ref, computed, watch } from "vue";
import {
  reqShowRepayList,
  reqRecharge,
  reqDaily,
  reqSelAllOrderList,
  reqShowWithdrawalList,
  reqHome,
  reqShowChargeList,
  reqGetChannelList
} from "@/api/index";
import { useUserStore, useSelectOptionsStore } from "@/store/index";
import { getDateAnd7DaysAgo } from "@/utils/index";
import {
  getOperateTypeLabel,
  getOrderStatusLabel,
} from "@/utils/selectOptions";

export const useRecharge = () => {
  const loading = ref(false);
  const selectOptionsStore = useSelectOptionsStore();
  const userStore = useUserStore();
  const tableConfigData = ref([
    // {
    //   prop: "payUser",
    //   label: "付款-名字",
    // },
    {
      prop: "currency",
      label: "貨幣",
      width: 80,
    },
    {
      prop: "money",
      label: "金額",
      width: 80,
    },
    {
      prop: "cost",
      label: "費用",
      width: 80,
    },
    {
      prop: "inPacketMoney",
      label: "到帳金額",
      width: 180,
    },
    {
      prop: "platformOrderId",
      label: "平台訂單編號",
    },
    {
      prop: "orderStatus",
      label: "狀態",
      width: 60,
    },
    // {
    //   prop: "origin",
    //   label: "渠道",
    // },
    // {
    //   prop: "description",
    //   label: "描述",
    // },
    {
      prop: "orderDateTime",
      label: "訂單時間",
    },
    {
      prop: "saveDateTime",
      label: "記帳時間",
    },
    // {
    //   prop: "payInfo",
    //   label: "支付信息",
    // },
  ]);
  const tableData = ref([]);
  const pageInfo = ref({
    totalPage: 0,
    currentPage: 1,
    pageSize: 10,
  });
  const validateMoney = (rule, value, callback) => {
    if (value === undefined || value === null || value === "") {
      callback(new Error("请输入支付金额"));
    } else if (isNaN(value)) {
      callback(new Error("支付金额必须是数字"));
    } else if (value > 5000) {
      callback(new Error("支付金额不能大于5000"));
    } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
      callback(new Error("支付金额小数点后不能超过两位"));
    } else {
      callback();
    }
  };
  const payForm = ref({
    country: "",
    payMethod: "",
    name: "",
    bankCode: "117",
    payMoney: "",
    currency: "",
    description: "",
    phone: "",
  });
  const payFormRules = ref({
    country: [{ required: true, message: "请选择國別", trigger: "blur" }],
    payMethod: [{ required: true, message: "请选择支付方式", trigger: "blur" }],
    name: [{ required: true, message: "请输入付款人姓名", trigger: "blur" }],
    bankCode: [{ required: true, message: "请输入銀行編碼", trigger: "blur" }],
    payMoney: [
      { required: true, message: "请输入支付金额", trigger: "blur" },
      {
        validator: validateMoney,
        trigger: "blur",
      },
    ],
    currency: [{ required: true, message: "请输入币种", trigger: "blur" }],
    description: [{ required: true, message: "请输入描述", trigger: "blur" }],
    phone: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号",
        trigger: "blur",
      },
    ],
  });

  // 当国别发生变化时请求对应的支付方式和币种
  watch(() => payForm.value.country, async (newVal) => {
    console.log("国别变化：", newVal);
    loading.value = true;
    const res = await reqGetChannelList(userStore.user_id, newVal);
    loading.value = false;
    console.log(res);
    payMethods.value = res.data.map((item) => ({
      label: item.pay_type_code_name,
      value: item.id,
    }));
    payForm.value.payMethod = "";
    payForm.value.currency = res.data[0].currency;
  });

  const CURRENCY_COUNTRY_MAP = {
    'VND': '越南',
    'MYR': '马来西亚'
  };
  const countries = computed(() => {
    return selectOptionsStore.currencyList.map((item) => ({
      value: CURRENCY_COUNTRY_MAP[item.currency],
      label: CURRENCY_COUNTRY_MAP[item.currency]
    }))
  });
  const payMethods = ref([]);
  // const currencies = selectOptionsStore.currencyList;

  const confirmPay = (formDom) => {
    formDom.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        const res = await reqRecharge({
          user_id: userStore.user_id,
          pay_type_code_id: payForm.value.payMethod,
          payphone: payForm.value.phone,
          payname: payForm.value.name,
          payemail: userStore.mail,
          country: payForm.value.country,
          order_amount: payForm.value.payMoney,
          currency: payForm.value.currency,
          bankcode: payForm.value.bankCode,
          desc: payForm.value.description,
        });
        clog("支付信息：", res);
        loading.value = false;
        // 跳转到支付页面
        // window.location.href = res.pay_link;
        window.open(res.pay_link, "_blank");
        payStep.value = 2;
        payInfoEno.value = res.pay_link;
      }
    });
  };

  const initData = async () => {
    loading.value = true;
    try {
      const res = await reqShowChargeList({
        user_id: userStore.user_id,
        page: pageInfo.value.currentPage,
      });
      clog("充值记录：", res);
      tableData.value = res.data.map((item) => ({
        payUser: "",
        currency: item.currency,
        money: item.order_amount,
        cost: item.merchant_cost,
        inPacketMoney: (item.order_amount - item.merchant_cost).toFixed(2),
        platformOrderId: item.platform_order,
        orderStatus: getOrderStatusLabel(item.status),
        origin: item.pay_type_code_name,
        description: item.description,
        orderDateTime: item.created_at,
        saveDateTime: item.receipt_time,
        payInfo: item.pay_link,
      }));
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
      loading.value = false;
    } catch (err) {
      clog("充值信息查询失败：", err);
      loading.value = false;
    }
  };
  initData();
  const payStep = ref(1); // 1|2
  const payInfoEno = ref("");
  return {
    loading,
    tableConfigData,
    tableData,
    pageInfo,
    payForm,
    payFormRules,
    countries,
    payMethods,
    // currencies,
    confirmPay,
    payStep,
    payInfoEno,
    initData,
  };
};

export const useDaily = () => {
  const loading = ref(false);
  const tableData = ref([]);
  let totalData = null;
  const userStore = useUserStore();
  const tableConfigData = ref([
    {
      prop: "consumeDate",
      label: "交易日期",
      width: 140,
    },
    {
      prop: "currency",
      label: "貨幣",
      width: 80,
    },
    {
      prop: "totalPay",
      label: "總交易筆數",
    },
    {
      prop: "agentPay",
      label: "代付金額",
    },
    {
      prop: "agentGet",
      label: "代收金額",
    },
    {
      prop: "agentPaySuccessNum",
      label: "代付成功筆數",
    },
    {
      prop: "agentPayFailNum",
      label: "代付失敗筆數",
    },
    {
      prop: "agentGetSuccessNum",
      label: "代收成功筆數",
    },
    {
      prop: "agentGetFailNum",
      label: "代收失敗筆數",
    },
    {
      prop: "agentGetPrice",
      label: "代收費用",
    },
    {
      prop: "agentPayPrice",
      label: "代付費用",
    },
  ]);

  const searchFormConfig = ref({
    currency: {
      name: "貨幣",
    },
    date: {
      name: "日期",
    },
  });
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });
  const initData = async ({
    currency = "",
    start_date = "",
    end_date = "",
  } = {}) => {
    loading.value = true;
    try {
      clog("查询参数:", {
        user_id: userStore.user_id,
        currency,
        start_date,
        end_date,
      });
      const res = await reqDaily({
        user_id: userStore.user_id,
        currency,
        startdata: start_date,
        enddata: end_date,
      });
      clog("日報信息：", res);
      totalData = res.data.map((item) => ({
        consumeDate: item.date,
        currency: item.currency,
        totalPay: item.w_count,
        agentPay: item.w_amount,
        agentGet: item.p_amount,
        agentPaySuccessNum: item.w_suc_count,
        agentPayFailNum: item.w_fail_count,
        agentGetSuccessNum: item.p_suc_count,
        agentGetFailNum: item.p_fail_count,
        agentGetPrice: item.w_merchant_cost,
        agentPayPrice: item.p_merchant_cost,
      }));
      tableData.value = totalData.slice(0, pageInfo.value.pageSize);
      pageInfo.value.totalPage = Math.ceil(
        res.data.length / pageInfo.value.pageSize
      );
      loading.value = false;
    } catch (err) {
      clog("日報信息查询失败：", err);
      loading.value = false;
    }
  };
  const { today, sevenDaysAgo } = getDateAnd7DaysAgo();
  initData({
    currency: "VND",
    start_date: sevenDaysAgo.dateStr,
    end_date: today.dateStr,
  });
  const prevPage = () => {
    if (pageInfo.value.currentPage <= 1) {
      pageInfo.value.currentPage = 1;
      return;
    }
    pageInfo.value.currentPage--;
    tableData.value = totalData.slice(
      (pageInfo.value.currentPage - 1) * pageInfo.value.pageSize,
      pageInfo.value.currentPage * pageInfo.value.pageSize
    );
  };

  const nextPage = () => {
    if (pageInfo.value.currentPage >= pageInfo.value.totalPage) {
      pageInfo.value.currentPage = pageInfo.value.totalPage;
      return;
    }
    pageInfo.value.currentPage++;
    tableData.value = totalData.slice(
      (pageInfo.value.currentPage - 1) * pageInfo.value.pageSize,
      pageInfo.value.currentPage * pageInfo.value.pageSize
    );
  };
  return {
    loading,
    tableData,
    tableConfigData,
    searchFormConfig,
    initData,
    pageInfo,
    prevPage,
    nextPage,
  };
};

export const useAgentPay = () => {
  const loading = ref(false);
  const tableData = ref([]);
  // const tableDataDisplay = ref([]);
  const userStore = useUserStore();
  const tableConfigData = ref([
    {
      prop: "platformOrderId",
      label: "平台訂單號",
    },
    // {
    //   prop: "merchatOrderId",
    //   label: "商戶訂單號",
    // },
    {
      prop: "currency",
      label: "貨幣",
      width: 80,
    },
    {
      prop: "receiveUser",
      label: "收款人姓名",
    },
    {
      prop: "bankName",
      label: "銀行名稱",
    },
    {
      prop: "backAccount",
      label: "銀行賬戶",
    },
    {
      prop: "money",
      label: "金額",
      width: 80,
    },
    {
      prop: "cost",
      label: "費用",
      width: 80,
    },
    {
      prop: "status",
      label: "狀態",
      width: 60,
    },
    // {
    //   prop: "description",
    //   label: "描述",
    // },
    {
      prop: "orderDateTime",
      label: "訂單時間",
    },
    {
      prop: "saveDateTime",
      label: "記帳時間",
    },
  ]);
  const pageInfo = ref({
    totalPage: 0,
    currentPage: 1,
    pageSize: 10,
  });
  const initData = async () => {
    loading.value = true;
    try {
      const res = await reqShowRepayList({
        user_id: userStore.user_id,
        page: pageInfo.value.currentPage,
      });
      clog("代付信息：", res);
      tableData.value = res.data.map((item) => ({
        platformOrderId: item.platform_order,
        // merchatOrderId: item.merchant_order,
        currency: item.currency,
        receiveUser: item.acc_name,
        bankName: item.bank_name,
        backAccount: item.acc_no,
        money: item.order_amount,
        cost: item.merchant_cost,
        status: getOrderStatusLabel(item.status),
        description: item.description,
        orderDateTime: item.created_at,
        saveDateTime: item.receipt_time,
      }));
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
      loading.value = false;
    } catch (err) {
      clog("代付信息查询失败：", err);
      loading.value = false;
    }
  };
  const prevPage = () => {
    if (pageInfo.value.currentPage > 1) {
      pageInfo.value.currentPage--;
      initData();
    }
  };
  const nextPage = () => {
    if (pageInfo.value.currentPage < pageInfo.value.totalPage) {
      pageInfo.value.currentPage++;
      initData();
    }
  };

  initData();
  return {
    loading,
    tableConfigData,
    pageInfo,
    prevPage,
    nextPage,
    tableData,
    initData,
  };
};

export const useDetail = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const tableData = ref([]);
  const tableConfigData = ref([
    {
      prop: "platformOrderId",
      label: "平台訂單號",
    },
    {
      prop: "merchantOrderId",
      label: "商戶訂單號",
    },
    {
      prop: "orderType",
      label: "類型",
    },
    {
      prop: "money",
      label: "金額",
    },
    // {
    //   prop: "payBefore",
    //   label: "交易前餘額",
    // },
    // {
    //   prop: "payAfter",
    //   label: "交易後餘額",
    // },
    {
      prop: "cost",
      label: "費用",
    },
    {
      prop: "status",
      label: "狀態",
    },
    {
      prop: "consumeDate",
      label: "訂單時間",
    },
    {
      prop: "saveDate",
      label: "記帳時間",
    },
  ]);

  const searchFormConfig = ref({
    currency: {
      name: "貨幣",
    },
    operateType: {
      name: "類型",
    },
    date: {
      name: "日期",
    },
    platformOrderId: {
      name: "平臺訂單號",
    },
    merchantOrderId: {
      name: "商戶訂單號",
    },
    orderStatus: {
      name: "狀態",
    },
  });

  const initData = async ({
    currency = "",
    type = "",
    startdata = "",
    enddata = "",
    platform_order = "",
    merchant_order = "",
    status = "",
    page = "1",
  } = {}) => {
    loading.value = true;
    clog("查询参数:", {
      user_id: userStore.user_id,
      currency,
      type,
      startdata,
      enddata,
      platform_order,
      merchant_order,
      status,
      page,
    });
    try {
      const res = await reqSelAllOrderList({
        user_id: userStore.user_id,
        currency,
        type,
        startdata,
        enddata,
        platform_order,
        merchant_order,
        status,
        page,
      });
      clog("订单信息：", res);
      tableData.value = res.data.map((item) => ({
        platformOrderId: item.platform_order,
        merchantOrderId: item.merchant_order,
        orderType: getOperateTypeLabel(item.type),
        money: item.order_amount,
        // payBefore: item.pay_before,
        // payAfter: item.pay_after,
        cost: item.merchant_cost,
        status: getOrderStatusLabel(item.status),
        consumeDate: item.created_at,
        saveDate: item.receipt_time,
      }));
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
      if (page === "1") {
        pageInfo.value.currentPage = 1;
      }
      loading.value = false;
    } catch (err) {
      clog("订单信息查询失败：", err);
      loading.value = false;
    }
  };
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });
  return {
    loading,
    tableData,
    tableConfigData,
    searchFormConfig,
    initData,
    pageInfo,
  };
};

export const useSum = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const tableDataTotal = ref([]);
  const tableData = ref([]);
  const tableConfigData = ref([
    {
      prop: "currency",
      label: "貨幣",
    },
    {
      prop: "inPacketMoney",
      label: "帳户金額",
    },
    {
      prop: "promiseMoney",
      label: "風險保證金",
    },
    {
      prop: "freezeMoney",
      label: "凍結金額",
    },
    {
      prop: "canUseMoney",
      label: "可用餘額",
    },
  ]);
  const pageInfo = ref({
    currentPage: 1,
    totalPage: 1,
    pageSize: 10,
  });
  const initData = async () => {
    try {
      loading.value = true;
      const res = await reqHome(userStore.user_id);
      loading.value = false;
      clog("账户信息：", res);
      tableDataTotal.value = res.data.map((item) => ({
        currency: item.currency,
        inPacketMoney: (
          parseFloat(item.risk_margin) +
          parseFloat(item.amount) +
          parseFloat(item.freeze_amount)
        ).toFixed(2),
        promiseMoney: item.risk_margin,
        freezeMoney: item.freeze_amount,
        canUseMoney: item.amount,
      }));
      tableData.value = tableDataTotal.value.slice(0, pageInfo.value.pageSize);
      pageInfo.value.totalPage = tableDataTotal.value.length;
    } catch (err) {
      clog("账户信息查询失败：", err);
      loading.value = false;
    }
  };
  const prevPage = () => {
    if (pageInfo.value.currentPage <= 1) {
      pageInfo.value.currentPage = 1;
      return;
    }
    pageInfo.value.currentPage--;
    tableData.value = tableDataTotal.value.slice(
      (pageInfo.value.currentPage - 1) * pageInfo.value.pageSize,
      pageInfo.value.currentPage * pageInfo.value.pageSize
    );
  };

  const nextPage = () => {
    if (pageInfo.value.currentPage >= pageInfo.value.totalPage) {
      pageInfo.value.currentPage = pageInfo.value.totalPage;
      return;
    }
    pageInfo.value.currentPage++;
    tableData.value = tableDataTotal.value.slice(
      (pageInfo.value.currentPage - 1) * pageInfo.value.pageSize,
      pageInfo.value.currentPage * pageInfo.value.pageSize
    );
  };
  initData(1);
  return {
    loading,
    tableData,
    tableConfigData,
    pageInfo,
    prevPage,
    nextPage,
    initData,
  };
};

export const useWithdraw = () => {
  const loading = ref(false);
  const userStore = useUserStore();
  const tableData = ref([]);

  const tableConfigData = ref([
    {
      prop: "platformOrderId",
      label: "平台訂單號",
    },
    {
      prop: "currency",
      label: "貨幣",
      width: 80,
    },
    {
      prop: "receiveUser",
      label: "收款人姓名",
    },
    {
      prop: "bankName",
      label: "銀行賬戶",
    },
    {
      prop: "orderAmount",
      label: "金額",
      width: 80,
    },
    {
      prop: "cost",
      label: "費用",
      width: 80,
    },
    {
      prop: "status",
      label: "狀態",
    },
    // {
    //   prop: "description",
    //   label: "描述",
    // },
    {
      prop: "orderDateTime",
      label: "訂單時間",
    },
    {
      prop: "saveDateTime",
      label: "記帳時間",
    },
  ]);
  const pageInfo = ref({
    totalPage: 0,
    currentPage: 1,
    pageSize: 10,
  });

  const initData = async () => {
    loading.value = true;
    try {
      const res = await reqShowWithdrawalList({
        user_id: userStore.user_id,
        page: pageInfo.value.currentPage,
      });
      loading.value = false;
      clog("提现记录：", res);
      tableData.value = res.data.map((item) => ({
        platformOrderId: item.platform_order,
        currency: item.currency,
        receiveUser: item.acc_name,
        bankName: item.bank_name,
        orderAmount: item.order_amount,
        cost: item.merchant_cost,
        status: getOrderStatusLabel(item.status),
        orderDateTime: item.created_at,
        saveDateTime: item.receipt_time,
      }));
      pageInfo.value.totalPage = Math.ceil(res.count / pageInfo.value.pageSize);
    } catch (err) {
      loading.value = false;
      clog("提现信息查询失败：", err);
    }
  };
  const prevPage = () => {
    if (pageInfo.value.currentPage > 1) {
      pageInfo.value.currentPage--;
      initData();
    }
  };
  const nextPage = () => {
    if (pageInfo.value.currentPage < pageInfo.value.totalPage) {
      pageInfo.value.currentPage++;
      initData();
    }
  };
  initData();
  return {
    loading,
    tableData,
    tableConfigData,
    pageInfo,
    initData,
    prevPage,
    nextPage,
  };
};
